<template>
  <view class="page-tab flex-row relative">
    <view v-for="(item, index) in tabs" :key="item.value" class="page-tab-item flex-item flex-row align-end justify-center padding-bottom-20" @click="changeTab(item.value, index)">
      <text class="text-28" :class="modelValue === item.value ? 'text-bold color-t1' : 'color-t2'">{{ item.label }}</text>
      <text v-if="item.num" class="text-28">({{ item.num }})</text>
    </view>
    <view class="line-box width-full">
      <view class="line" id="line" :class="{ animation }" :style="{ left }" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { getElementInfo } from '@/common/util'
import type { AnyObject } from '@/common/types'

interface IProps{
  tabs: AnyObject[]
  modelValue: number
}

const props = withDefaults(defineProps<IProps>(), {
  tabs: () => ([]),
  modelValue: 0
})

const $emit = defineEmits(['change', 'update:modelValue'])

const tabInx = ref(0)
const left = computed(() => lefts[tabInx.value] + 'px')
const lefts = reactive<number[]>([])
const animation = ref(false)
async function getBarLefts() {
  const instance = getCurrentInstance()
  await nextTick()
  const res = await Promise.all([getElementInfo('.page-tab-item', instance), getElementInfo('#line', instance)])
  const tabs = res[0]
  const barWidthHalf = res[1].width / 2
  tabs.forEach((item: AnyObject) => {
    lefts.push(item.left + item.width / 2 - barWidthHalf)
  })
  await nextTick()
  animation.value = true
}

onMounted(getBarLefts)
watch(
  () => props.tabs,
  getBarLefts
)

let disabled = false
const changeTab = (value: number, index: number) => {
  if (props.modelValue === value) return
  if (!disabled) {
    disabled = true
    tabInx.value = index
    console.log(tabInx.value)
    $emit('change')
    $emit('update:modelValue', value)
    setTimeout(() => {
      disabled = false
    }, 300)
  }
}

</script>

<style scoped lang="scss">
.page-tab{
  background: $color-white;
  @include position(sticky, 0, 0, $z-index: 10);

  .page-tab-item{
    height: 104rpx;
  }

  .line-box{
    height: 4rpx;
    @include position(absolute, $left: 0, $bottom: 0, $z-index: 2);

    .line{
      width: 56rpx;
      height: 4rpx;
      border-radius: 2rpx;
      background: $color-primary;
      @include position(absolute, $bottom: 0, $z-index: 2);

      &.animation{
        transition: all .3s ease-in-out;
      }

    }

  }
}
</style>
